/*
 * Copyright (c) 2018. Beyondsoft Corporation.
 * All Rights Reserved.
 *
 * BEYONDSOFT CONFIDENTIALITY
 *
 * The information in this file is confidential and privileged from Beyondsoft Corporation,
 * which is intended only for use solely by Beyondsoft Corporation.
 * Disclosure, copying, distribution, or use of the contents of this file by persons other than Beyondsoft Corporation
 * is strictly prohibited and may violate applicable laws.
 */
package com.unifiedlibrary.amall_page.base.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.base.common.basemodule.LoadingDialog;
import com.base.common.uiUtils.UiUtils;
import com.unifiedlibrary.amall_page.R;
import com.unifiedlibrary.amall_page.base.MainApp;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xzk
 * @data 2019/5/23
 * @email xiezhengkun@beyondsoft.com
 * @remark   少部分不带mvp模式的act使用
 */
public abstract class BaseNoModelActivity extends AppCompatActivity {
    private Map<Integer, Runnable> allowablePermissionRunnables = new HashMap<>();
    private Map<Integer, Runnable> disallowablePermissionRunnables = new HashMap<>();
    protected Activity context;
    private LoadingDialog loadingDialog;
//    private Unbinder bind;

    /**
     * 设置修改语言
     *
     * @param newBase
     */
    @Override
    protected void attachBaseContext(Context newBase) {
//        Context context = LanContextWrapper.wrap(newBase);
        super.attachBaseContext(newBase);
    }

    /**
     * 重启应用
     */
    protected void rebotApp() {
        //大于7.0系统需要重启应用
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
//            MainApp.finishAllActivity();
//            Intent intent = new Intent(this, SplashActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
        }else{
            recreate();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(isLockingPortrait()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        }
        super.onCreate(savedInstanceState);
        getUrl();
        if(isHidenStatusbar()){
            //取消状态栏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }else {
//            UiUtils.setStatusBarTransparent(this);
        }

        context = this;

        loadingDialog = new LoadingDialog(context);

        setContentView(getLayoutResourceID());
//        bind = ButterKnife.bind(this);
        initializeData(savedInstanceState);
//        getStateBar3();
//        LanContextWrapper lanContextWrapper = new LanContextWrapper(this);
//        lanContextWrapper.saveLanguageByApplication(this);
    }

//    private void getStateBar3(){
//        int result = 0;
//        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
//        if (resourceId > 0) {
//            result = this.getResources().getDimensionPixelSize(resourceId);
//        }
//        LogUtils.d("状态栏高度3：" + result + "px");
//
//        View byId = findViewById(R.id.v_title_on);
//        try{
//            if(byId!=null){
//                ViewGroup.LayoutParams params = byId.getLayoutParams();
//                params.height=result;
//                LogUtils.d("setAct:"+this.getLocalClassName()+"-->"+params.height);
//                byId.setLayoutParams(params);
//            }else {
//                LogUtils.d("actName:"+this.getLocalClassName());
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            LogUtils.d("actName:"+this.getLocalClassName());
//        }
//    }

    /**
     * 补充获取请求地址信息，避免在出现加载异常时，无法获取当前请求路径
     */
    private void getUrl(){
//        if(TextUtils.isEmpty(NetConstant.API_BASE_TEST)){
//            NetConstant.API_BASE_TEST= SharedPreferencesUtil.getInstance().getString(Constant.User.EMPLOYEE_IP);
//            if(TextUtils.isEmpty(NetConstant.API_BASE_TEST)){
//                NetConstant.API_BASE_TEST=NetConstant.NetEnvirment.getProdEnvir();
//            }
//        }
    }

    /**
     * 用于控制当前界面是否隐藏状态栏（子类重写改变）
     *
     * @return
     */
    protected boolean isHidenStatusbar(){
        return false;
    }

    /**
     * 是否锁定竖屏
     * @return
     */
    protected boolean isLockingPortrait(){
        return true;
    }

//    /**
//     * 统计确定按钮显示的数值
//     * @param button
//     * @param typeVos
//     * @param <T>
//     */
//    public <T> void getCheckSize(Button button, List<T> typeVos) {
//        int checkSize = 0;
//        for (int i = 0; i < typeVos.size(); i++) {
//            T t = typeVos.get(i);
//            Class<?> aClass = t.getClass();
//            try {
//                Field checked = aClass.getDeclaredField("checked");
//                // 将目标属性设置为可以访问
//                checked.setAccessible(true);
//                boolean aBoolean = checked.getBoolean(t);
//                if (aBoolean) {
//                    checkSize++;
//                }
//            } catch (NoSuchFieldException e) {
//                e.printStackTrace();
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            }
//        }
//        if(checkSize >0){
//            button.setText(context.getString(R.string.str_sure)+"("+checkSize+")");
//        }else {
//            button.setText(context.getString(R.string.str_sure));
//        }
//    }
//    /**
//     *
//     * @param button
//     * @param typeVos
//     * @param <T>
//     */
//    public<T> void getCheckSize(Button button, List<T> typeVos){
//        int checkSize=0;
//        for (int i = 0; i < typeVos.size(); i++) {
//            T t = typeVos.get(i);
//            if(t instanceof WorkerTypeBean.DataBean.OrderTypeVosBean ){
//                if(((WorkerTypeBean.DataBean.OrderTypeVosBean) t).isChecked()){
//                    checkSize++;
//                }
//            }else if(t instanceof WorkerTypeBean.DataBean.DeviceTypeVosBean ){
//                if(((WorkerTypeBean.DataBean.DeviceTypeVosBean) t).isChecked()){
//                    checkSize++;
//                }
//            }
//        }
//        if(checkSize >0){
//            button.setText(context.getString(R.string.str_surein) + "(" + checkSize + ")");
//        }else {
//            button.setText(context.getString(R.string.str_surein));
//        }
//    }

    /**
     * 请求权限
     *
     * @param id                   请求授权的id 唯一标识即可
     * @param permissions           请求的权限
     * @param allowableRunnable    同意授权后的操作
     * @param disallowableRunnable 禁止权限后的操作
     */
    public void requestPermission(int id, String[] permissions, Runnable allowableRunnable, Runnable disallowableRunnable) {
        if (allowableRunnable == null) {
            throw new IllegalArgumentException("allowableRunnable == null");
        }
        allowablePermissionRunnables.put(id, allowableRunnable);
        if (disallowableRunnable != null) {
            disallowablePermissionRunnables.put(id, disallowableRunnable);
        }

        //版本判断
        if (Build.VERSION.SDK_INT >= 23) {
            //减少是否拥有权限
            boolean isNoPermission=false;
            for (int i = 0; i < permissions.length; i++) {
                String permission=permissions[i];
                int checkCallPhonePermission = ContextCompat.checkSelfPermission(getApplicationContext(), permission);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    isNoPermission=true;
                    break;
                }
            }
            if (isNoPermission) {
                //弹出对话框接收权限
                ActivityCompat.requestPermissions(this, permissions, id);
                return;
            } else {
                allowableRunnable.run();
            }
        } else {
            allowableRunnable.run();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        try {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Runnable allowRun = allowablePermissionRunnables.get(requestCode);
                if (allowRun != null)
                    allowRun.run();
            } else {
                Runnable disallowRun = disallowablePermissionRunnables.get(requestCode);
                if (disallowRun != null)
                    disallowRun.run();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void hideInputSoft(View v) {
        InputMethodManager imm = (InputMethodManager)
            getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v != null)
                Log.i("dian", v.getClass().getSimpleName());
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        try {
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            Log.i("------", "isShouldHideInput: base");
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        //打开软键盘
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void startActivityAndFinishThis(Activity activity,Class<?> cls) {
        Intent intent = new Intent(activity, cls);
        startActivity(intent);
        activity.finish();
    }

    public void startActivityAndFinishThis(Activity activity,Class<?> cls,Bundle bundle) {
        Intent intent = new Intent(activity,cls);
        intent.putExtras(bundle);
        startActivity(intent);
        activity.finish();
    }

    public void startActivity(Activity activity,Class<?> cls) {
        Intent intent = new Intent(activity,cls);
        startActivity(intent);
    }

    public void startActivity(Activity activity,Class<?> cls,Bundle bundle) {
        Intent intent = new Intent(activity, cls);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public abstract int getLayoutResourceID();

    public abstract void initializeData(Bundle savedInstanceState);

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            this.finish();
            return true;
        }
        return super.onKeyDown(
            keyCode,
            event
                              );
    }

    public void showLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.showDialog();
        }

    }

    public void removeLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismissDialog();
        }
    }

    @Override
    protected void onDestroy() {
        //清除dialog
        if(loadingDialog!= null){
            loadingDialog.recycleSource();
            loadingDialog=null;
        }
        super.onDestroy();
//        bind.unbind();
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

}
